//
//  XLComposePicView.swift
//  SinaWeibo
//
//  Created by 李凯 on 16/9/12.
//  Copyright © 2016年 kevin. All rights reserved.
//

import UIKit
import SVProgressHUD

let cellid = "cellid"

class XLComposePicView: UICollectionView {
    
    //初始化一个数组, 用来保存用户添加的图片
    var images: [UIImage] = [UIImage]()
    
    //定义一个闭包
    var addImgBtnClickClosure: (() -> ())?

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI() {
        self.register(XLComposePicViewCell.self, forCellWithReuseIdentifier: cellid)
        self.dataSource = self
        self.delegate = self
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let itemMargin: CGFloat = 5
        let itemWH = (self.frame.width - 2 * itemMargin) / 3

        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin
    }
    
    func addImage(image: UIImage) {
        if images.count > 9 {
            SVProgressHUD.showError(withStatus: "图片数量超出限制")
        }else{
            images.append(image)
            reloadData()
        }
    }

}

extension XLComposePicView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    //监听按钮点击
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        //判断是否是最后一个cell点击了
        if indexPath.item == images.count {
            //执行闭包
            addImgBtnClickClosure?()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (images.count == 0 || images.count == 9) ? images.count : images.count+1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellid, for: indexPath) as! XLComposePicViewCell
        
        if indexPath.item < self.images.count{
            cell.image = images[indexPath.item]
        }else{
            cell.image = nil
        }
        
        cell.deleteBtnClickClosure = {
            //回调
            self.images.remove(at: indexPath.item)
            //刷新数据
            self.reloadData()
            
        }
        return cell
    }
}
